package com.yinxing.webapi.code.service.sys;

import com.yinxing.framework.mybatis.TemplateService;
import com.yinxing.webapi.code.entity.sys.SysRole;
import com.yinxing.webapi.code.mapper.sys.SysRoleMapper;
import com.yinxing.webapi.code.mapper.sys.SysUserroleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.Role;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ISysRoleService extends TemplateService<SysRole> {

    @Autowired
    private ISysRolemenuService sysRolemenuService;

    @Autowired
    private ISysUserroleService sysUserroleService;

    @Autowired
    private ISysRolepermissionService sysRolepermissionService;

    private SysRoleMapper getMapper() {
        return (SysRoleMapper) baseMapper;
    }

    /**
     * 插入数据
     * @param entity 实体类
     */
    public boolean insert(SysRole entity) {
        entity.setCreateTime_(LocalDateTime.now());
        return super.insert(entity);
    }

    /**
     * 启用|禁用
     * @param id 主键ID
     */
    public void stopById(Long id) {
        SysRole record = baseMapper.selectById(id);
        if(record != null) {
            record.setStop_(!record.getStop_());
            this.updateById(record);
        }
    }

    /**
     * 删除角色(同时删除绑定菜单和绑定用户)
     * @param id 角色ID
     */
    public boolean deleteById(Long id) {
        //删除角色绑定的菜单关系
        sysRolemenuService.deleteByRoleId(id);
        //删除角色绑定的用户关系
        sysUserroleService.deleteByRoleId(id);
        //删除角色绑定的权限关系
        sysRolepermissionService.deleteByRoleId(id);
        return super.deleteById(id);
    }

    /**
     * 批量删除角色(同时删除绑定菜单和绑定用户)
     * @param ids 角色ID集合
     */
    public void deleteBatchById(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            this.deleteById(ids[i]);
        }
    }

    /**
     * 查询用户绑定的角色信息(不包含已经禁用的角色)
     * @param sysUserId 用户ID
     */
    public List<SysRole> selectRolesBySysUserId(long sysUserId) {
        return this.getMapper().selectRolesBySysUserId(sysUserId);
    }

    /**
     * 查询用户绑定的角色编码集合(不包含已经禁用的角色)
     * @param sysUserId 用户ID
     */
    public Set<String> selectRoleCodesBySysUserId(long sysUserId) {
        return selectRolesBySysUserId(sysUserId)
                .stream()
                .map(sysRole -> sysRole.getRoleCode_())
                .collect(Collectors.toSet());
    }


}